<template>
  <view class="container">
    <!-- 加载状态遮罩 -->
    <view class="loading-mask" v-if="loadingLocation">
      <text>正在获取位置信息...</text>
    </view>
    
    <!-- 错误提示 -->
    <view class="error-tip" v-if="locationError">
      <text class="error-text">位置获取失败，请确保已授予位置权限</text>
      <button class="retry-btn" @click="getUserLocation">重试</button>
    </view>
    
    <!-- 地图容器（使用uni-map组件） -->
    <uni-map
      id="map-container"
      class="map-container"
      v-if="!loadingLocation"
      :latitude="mapCenter.latitude"
      :longitude="mapCenter.longitude"
      :scale="scale"
      :markers="mapMarkers"
      :polygons="fencePolygons"
      @markertap="onMarkerTap"
    ></uni-map>
    
    <!-- 围栏信息 -->
    <view class="fence-info" v-if="fenceArea && fencePerimeter">
      <text>围栏面积: {{ fenceArea.toFixed(2) }} m²</text>
      <text>围栏周长: {{ fencePerimeter.toFixed(2) }} m</text>
    </view>
    
    <!-- 标记状态提示 -->
    <view class="marker-status" v-if="mapMarkers.length === 0">
      <text>未找到牛只位置</text>
    </view>
    
    <!-- 信息面板 -->
    <view class="info-view" v-if="!loadingLocation">
      <view class="info-header">
        <image 
          class="cow-icon" 
          :src="cowInfo.isInFence ? '/static/imgs/cow.png' : '/static/imgs/cow.png'" 
          mode="aspectFill"
        ></image>
        <text class="cow-number">牛只编号: {{ cowInfo.imei || '未获取' }}</text>
        <text class="switch" @click="toggleCow">切换</text>
      </view>
      
      <view class="status-indicator">
        <text class="status-label">状态:</text>
        <text class="status-value" :class="cowInfo.isInFence ? 'in-fence' : 'out-fence'">
          {{ cowInfo.isInFence ? '在围栏内' : '越界警告' }}
        </text>
      </view>
      
      <view class="imei-info">IMEI: {{ cowInfo.imei || '未获取' }}</view>
      <view class="info-item">定位时间: {{ cowInfo.locationTime || '未获取' }}</view>
      <view class="info-item">定位地点: {{ cowInfo.locationAddress || '未获取' }}</view>
      <view class="info-item">距 离: {{ (cowInfo.distance * 1).toFixed(2) }}km</view>
      
      <button class="flash-bell" @click="flashAndRing" :disabled="!cowInfo.imei">
        <text class="btn-icon"><i class="fa fa-bell"></i></text>
        <text class="btn-text">闪光响铃</text>
      </button>
      
      <view class="nav-buttons">
        <button class="map-nav" @click="mapNavigation" :disabled="!cowInfo.imei">
          <text class="btn-icon"><i class="fa fa-map-o"></i></text>
          <text class="btn-text">地图导航</text>
        </button>
        <button class="straight-nav" @click="straightNavigation" :disabled="!cowInfo.imei">
          <text class="btn-icon"><i class="fa fa-arrows-h"></i></text>
          <text class="btn-text">直线导航</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { getMapFence } from '@/utils/api/map.js';
const QQMapWX = require('../../static/libs/qqmap-wx-jssdk.min.js')

export default {
  data() {
    return {
      mapKey: 'NIUBZ-K2ICQ-3R753-4AVVQ-5HWHV-4KF36', // 请替换为你的真实Key
      qqmapsdk: null, // 腾讯地图SDK实例
      
      mapCenter: { latitude: 39.90923, longitude: 116.397428 },
      scale: 14,
      mapMarkers: [], // 地图标记（适配uni-map格式）
      fencePolygons: [], // 围栏多边形（适配uni-map格式）
      
      fencePaths: [], // 原始围栏坐标点
      fenceArea: 0,
      fencePerimeter: 0,
      
      cowInfo: {
        imei: '',
        locationTime: '',
        locationAddress: '',
        distance: 0,
        isInFence: false
      },
      
      loadingLocation: true,
      locationError: false,
      currentCowId: null,
      cowList: [],
      
      userLocation: { latitude: 0, longitude: 0 }, // 用户当前位置
      mapReady: false // 地图初始化完成标志
    };
  },

  onLoad() {
    this.initQQMap(); // 初始化腾讯地图SDK
    this.loadFenceData(); // 加载围栏和牛数据
  },

  onReady() {
    this.initMap(); // 初始化地图组件
    this.getUserLocation(); // 获取用户位置
  },

  methods: {
    // 初始化腾讯地图SDK
    initQQMap() {
      this.qqmapsdk = new QQMapWX({ key: this.mapKey });
    },

    // 初始化地图组件
    initMap() {
      // 使用uni.createMapContext创建地图上下文
      this.mapContext = uni.createMapContext('map-container');
      this.mapReady = true;
      this.fitMapToFence(); // 调整地图视野
    },

    // 获取用户当前位置（使用uni.getLocation）
    getUserLocation() {
      uni.getLocation({
        type: 'wgs84', // 返回GPS坐标（腾讯地图需GCJ-02坐标，后续需转换）
        success: (res) => {
          // 转换坐标（WGS84转GCJ-02）
          const converted = this.convertWgs84ToGcj02(res.latitude, res.longitude);
          this.userLocation = { 
            latitude: converted.lat, 
            longitude: converted.lng 
          };
          this.updateUserMarker(); // 更新用户标记
          this.loadingLocation = false;
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          this.loadingLocation = false;
          this.locationError = true;
          this.loadDefaultCowLocation(); // 加载测试数据
        }
      });
    },

    // 更新用户位置标记（适配uni-map）
    updateUserMarker() {
      this.mapMarkers = this.mapMarkers.filter(marker => marker.id !== 'user-location'); // 清除旧标记
      this.mapMarkers.push({
        id: 'user-location',
        latitude: this.userLocation.latitude,
        longitude: this.userLocation.longitude,
        iconPath: '/static/imgs/seat.png',
        width: 30,
        height: 30,
        label: {
          content: '当前位置',
          color: '#fff',
          bgColor: 'rgba(0, 122, 255, 0.8)'
        }
      });
    },

    // 加载围栏数据及牛位置
    async loadFenceData() {
      try {
        const { data } = await getMapFence();
        if (data.code !== 200) throw new Error('数据加载失败');
        
        // 解析围栏数据（转换坐标格式）
        this.parseFenceInfo(data.data.fenceInfo);
        // 解析牛位置数据（转换坐标格式）
        this.parseCowLocation(data.data.locationInfo);
        // 解析面积周长
        this.parseNumInfo(data.data.NumInfo);
        
        if (this.cowList.length) {
          this.currentCowId = this.cowList[0].id;
          this.updateCurrentCowInfo();
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        this.handleLocationError('数据加载失败，请重试');
      }
    },

    // 解析围栏几何数据（转换为uni-map多边形格式）
    parseFenceInfo(fenceInfo) {
      if (!fenceInfo.length) return;
      const fenceData = JSON.parse(fenceInfo[0].F_Map);
      this.fencePaths = fenceData.paths.map(point => ({
        latitude: point.lat, 
        longitude: point.lng
      })); // 直接使用GCJ-02坐标
      
      // 构建uni-map多边形数据
      this.fencePolygons = [{
        points: this.fencePaths,
        strokeColor: '#007AFF',
        strokeWidth: 3,
        fillColor: 'rgba(0, 122, 255, 0.1)'
      }];
    },

    // 解析牛只位置数据（转换为uni-map标记格式）
    parseCowLocation(locationInfo) {
      this.cowList = [];
      this.mapMarkers = []; // 清空旧标记
      
      if (!locationInfo.length) return;
      
      locationInfo.forEach(cow => {
        const lat = parseFloat(cow.lat);
        const lng = parseFloat(cow.lng);
        const isInFence = cow.F_Isster === 1;
        
        // 转换坐标（假设接口返回WGS84，需转为GCJ-02）
        const converted = this.convertWgs84ToGcj02(lat, lng);
        
        this.mapMarkers.push({
          id: cow.F_IMEI,
          latitude: converted.lat,
          longitude: converted.lng,
          iconPath: isInFence ? '/static/imgs/cow.png' : '/static/imgs/cow.png',
          width: 40,
          height: 40,
          title: `牛只${cow.F_IMEI}`,
          callout: {
            content: `牛只${cow.F_IMEI}\n状态：${isInFence ? '在围栏内' : '越界'}`,
            display: 'ALWAYS'
          }
        });
        
        this.cowList.push({
          id: cow.F_IMEI,
          lat: converted.lat,
          lng: converted.lng,
          isInFence,
          name: `牛只${cow.F_IMEI}`
        });
      });
    },

    // 坐标转换：WGS84转GCJ-02（腾讯地图使用GCJ-02坐标系）
    convertWgs84ToGcj02(lat, lng) {
      // 简易转换算法（实际项目建议使用腾讯地图API转换）
      const x = lng, y = lat;
      const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
      const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
      const gcjLat = z * Math.sin(theta);
      const gcjLng = z * Math.cos(theta);
      return { lat: gcjLat, lng: gcjLng };
    },

    // 更新当前选中的牛信息
    updateCurrentCowInfo() {
      const currentCow = this.cowList.find(cow => cow.id === this.currentCowId);
      if (!currentCow) return;
      
      this.cowInfo = {
        imei: currentCow.id,
        locationTime: this.formatDateTime(new Date()),
        locationAddress: '获取中...',
        distance: this.calculateDistance(
          this.userLocation.latitude,
          this.userLocation.longitude,
          currentCow.lat,
          currentCow.lng
        ).toFixed(2),
        isInFence: currentCow.isInFence
      };
      
      // 逆地址解析
      this.getAddressFromAPI(currentCow.lat, currentCow.lng).then(address => {
        this.cowInfo.locationAddress = address;
      });
      
      // 定位地图到牛位置
      this.mapCenter = { 
        latitude: currentCow.lat, 
        longitude: currentCow.lng 
      };
    },

    // 调用腾讯地图逆地址解析
    getAddressFromAPI(lat, lng) {
      return new Promise((resolve) => {
        this.qqmapsdk.reverseGeocoder({
          location: { latitude: lat, longitude: lng },
          success: (res) => {
            resolve(res.result.address || '未知地址');
          },
          fail: () => {
            resolve('地址获取失败');
          }
        });
      });
    },

    // 计算两点距离（单位：km）
    calculateDistance(lat1, lon1, lat2, lon2) {
      const R = 6371;
      const dLat = (lat2 - lat1) * Math.PI / 180;
      const dLon = (lon2 - lon1) * Math.PI / 180;
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      return R * c; // 单位：km
    },
    
    // 更新所有牛只与用户的距离
    updateCowDistance() {
      this.cowList.forEach(cow => {
        cow.distance = this.calculateDistance(
          this.userLocation.latitude,
          this.userLocation.longitude,
          cow.lat,
          cow.lng
        ).toFixed(2);
      });
      
      if (this.currentCowId) {
        const currentCow = this.cowList.find(cow => cow.id === this.currentCowId);
        if (currentCow) {
          this.cowInfo.distance = currentCow.distance;
        }
      }
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    },
    
    // 调用腾讯地图API获取地址
    getAddressFromAPI(lat, lng) {
      return new Promise((resolve, reject) => {
        if (!this.mapKey) {
          resolve('未配置地图密钥');
          return;
        }
        
        // 使用腾讯地图逆地址解析
        const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${this.mapKey}&get_poi=0`;
        
        uni.request({
          url: url,
          success: (res) => {
            if (res.data && res.data.status === 0 && res.data.result) {
              resolve(res.data.result.address);
            } else {
              resolve('未知地址');
            }
          },
          fail: (err) => {
            console.error('获取地址失败:', err);
            resolve('地址获取失败');
          }
        });
      });
    },
    
    // 闪光响铃功能
    flashAndRing() {
      if (!this.cowInfo.imei) return;
      
      uni.showLoading({
        title: '正在发送指令...',
        mask: true
      });
      
      // 模拟API调用
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: `已向 ${this.cowInfo.imei} 发送闪光响铃指令`,
          icon: 'none',
          duration: 3000
        });
      }, 1500);
    },
    
    // 地图导航功能
    mapNavigation() {
      if (!this.cowInfo.imei) return;
      
      const currentCow = this.cowList.find(cow => cow.id === this.cowInfo.imei);
      if (!currentCow) return;
      
      // 使用腾讯地图SDK的导航功能
      uni.openLocation({
        latitude: currentCow.lat,
        longitude: currentCow.lng,
        name: `牛只${currentCow.id}`,
        address: this.cowInfo.locationAddress,
        scale: 18,
        success: () => {
          console.log('打开地图导航成功');
        },
        fail: (err) => {
          console.error('打开地图导航失败:', err);
          uni.showToast({
            title: '打开地图导航失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 直线导航功能
    straightNavigation() {
      if (!this.cowInfo.imei) return;
      
      const currentCow = this.cowList.find(cow => cow.id === this.cowInfo.imei);
      if (!currentCow) return;
      
      // 清除旧的导航线
      if (this.navigationLine) {
        this.navigationLine.remove();
      }
      
      // 创建从用户位置到牛位置的直线
      this.navigationLine = new TMap.Polyline({
        path: [
          { lat: this.userLocation.latitude, lng: this.userLocation.longitude },
          { lat: currentCow.lat, lng: currentCow.lng }
        ],
        strokeColor: "#FF3333",
        strokeWeight: 3,
        strokeOpacity: 0.8,
        strokeStyle: 'dashed',
        zIndex: 200
      });
      
      this.navigationLine.addTo(this.map);
      
      // 显示导航提示
      uni.showModal({
        title: '直线导航',
        content: `已为您标记到牛只的直线方向，距离约 ${this.cowInfo.distance}km。`,
        confirmText: '知道了',
        showCancel: false
      });
    },
    
    // 处理位置错误
    handleLocationError(message) {
      console.error('位置错误:', message);
      this.loadingLocation = false;
      this.locationError = true;
      
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 3000
      });
    },
    
    // 加载默认牛位置数据（用于测试）
    loadDefaultCowLocation() {
      console.log('使用默认牛位置数据');
      
      this.fencePaths = [
        { lng: 116.395, lat: 39.910 },
        { lng: 116.395, lat: 39.905 },
        { lng: 116.400, lat: 39.905 },
        { lng: 116.400, lat: 39.910 }
      ];
      
      this.cowList = [
        { id: 'A001', name: '奶牛A', isInFence: true, lat: 39.907, lng: 116.397 },
        { id: 'B002', name: '奶牛B', isInFence: false, lat: 39.903, lng: 116.402 }
      ];
      
      this.markers = this.cowList.map(cow => ({
        id: cow.id,
        position: { lat: cow.lat, lng: cow.lng },
        iconPath: cow.isInFence ? '@/static/imgs/cow.png' : '@/static/imgs/cow.png',
        width: 40,
        height: 40,
        title: cow.name,
        callout: {
          content: `${cow.name}\n状态：${cow.isInFence ? '在围栏内' : '越界'}`,
          display: 'ALWAYS'
        }
      }));
      
      this.fenceArea = 5000;
      this.fencePerimeter = 1200;
      
      if (this.cowList.length > 0) {
        this.currentCowId = this.cowList[0].id;
        this.updateCurrentCowInfo();
      }
      
      // 在地图准备好后绘制围栏和标记
      if (this.mapReady) {
        this.drawFenceOnMap();
        this.addMarkersToMap();
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 0;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

.map-container {
  margin-bottom: 0;
  height: calc(100vh - 250px);
  position: relative;
}

.fence-info {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 5px;
  z-index: 100;
  font-size: 14px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.marker-status {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  z-index: 10;
  font-size: 14px;
}

.info-view {
  background-color: #fff;
  padding: 15px;
  border-radius: 15px 15px 0 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.info-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.cow-icon {
  width: 45px;
  height: 45px;
  margin-right: 12px;
  border-radius: 50%;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.cow-number {
  flex: 1;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.switch {
  color:#0BCB75;
  font-size: 16px;
  padding: 5px 10px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.switch:hover {
  background-color: #f0f7ff;
}

.status-indicator {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.status-label {
  color: #666;
  font-size: 14px;
  margin-right: 8px;
}

.status-value {
  font-size: 16px;
  font-weight: 500;
  padding: 3px 8px;
  border-radius: 5px;
}

.in-fence {
  background-color: #e6ffea;
  color: #00b42a;
}

.out-fence {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.imei-info {
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.info-item {
  margin-bottom: 8px;
  color: #333;
  font-size: 15px;
  display: flex;
  align-items: center;
}

.info-item:before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #0BCB75;
  margin-right: 8px;
}

.flash-bell {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: 12px;
  background-color: #fff;
  border: 2px solid #0BCB75;
  color: #0BCB75;
  border-radius: 10px;
  margin: 15px 0;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
}

.flash-bell:hover {
  background-color: #f0f7ff;
}

.flash-bell:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-icon {
  margin-right: 8px;
}

.nav-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.map-nav,
.straight-nav {
  flex: 1;
  padding: 12px;
  background-color: #0BCB75;
  color: #fff;
  border: none;
  border-radius: 10px;
  margin-right: 10px;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.map-nav:last-child,
.straight-nav:last-child {
  margin-right: 0;
}

.map-nav:hover,
.straight-nav:hover {
  background-color: #09b368;
}

.map-nav:disabled,
.straight-nav:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.user-marker-label {
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 12px;
  padding: 2px 5px;
  border-radius: 3px;
  white-space: nowrap;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  flex-direction: column;
}

.loading-mask text {
  color: #333;
  font-size: 16px;
  margin-top: 10px;
}

.error-tip {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 99;
  text-align: center;
}

.error-text {
  color: #ff3b30;
  font-size: 16px;
  margin-bottom: 15px;
  display: block;
}

.retry-btn {
  background-color: #007AFF;
  color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 16px;
}
</style>